package com.wq.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wq.Result;
import com.wq.dto.SendSmsDTO;
import com.wq.dto.UserDTO;
import com.wq.dto.UserLoginDTO;
import com.wq.entity.User;
import com.wq.handlers.BaseContext;
import com.wq.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wq
 * @since 2025-11-09
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;


    @PostMapping("/login")
    public Result<String> login(@RequestBody UserLoginDTO userLoginDTO) {
        String token = userService.login(userLoginDTO);
        if("账号被禁用，请联管理员".equals(token)){
            return Result.fail(token);
        }
        return Result.success(token);
    }

    @PostMapping("/getCode")
    public Result<Object> getCode(@RequestBody SendSmsDTO sendSmsDTO){
        userService.sendCode(sendSmsDTO.getPhone());
        //todo 记录场景使用次数
        return Result.success();
    }

    @GetMapping("/info")
    public Result<User> getUserInfo() {
        Long id = BaseContext.getCurrentId();
        User user = userService.getById(id);
        return Result.success(user);
    }

    /**
     * 根据ID查询用户信息（内部调用）
     */
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        User user = userService.getById(id);
        return Result.success(user);
    }

    /**
     * 分页查询用户列表
     */
    @GetMapping("/list")
    public Result<Page<User>> getUserList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword) {
        Page<User> page = userService.getUserList(pageNum, pageSize, keyword);
        return Result.success(page);
    }

    /**
     * 添加用户
     */
    @PostMapping("/add")
    public Result<User> addUser(@RequestBody UserDTO userDTO) {
        User user = userService.addUser(userDTO);
        return Result.success(user);
    }

    /**
     * 更新用户
     */
    @PutMapping("/update/{id}")
    public Result<Boolean> updateUser(@PathVariable Integer id, @RequestBody UserDTO userDTO) {
        Boolean result = userService.updateUser(id, userDTO);
        return Result.success(result);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/delete/{id}")
    public Result<Boolean> deleteUser(@PathVariable Integer id) {
        Boolean result = userService.deleteUser(id);
        return Result.success(result);
    }

    /**
     * 启用/禁用用户
     */
    @PutMapping("/status/{id}")
    public Result<Boolean> updateUserStatus(
            @PathVariable Integer id,
            @RequestParam Byte status) {
        Boolean result = userService.updateUserStatus(id, status);
        return Result.success(result);
    }



}
